﻿using System.Linq;
using Coder.Workflow;
using JwtWebApi.Data;
using JwtWebApi.Filters;
using JwtWebApi.Models.ViewModel;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;

namespace JwtWebApi.Controllers
{
    [Authorize]
    [Route("[controller]")]
    [ApiController]
    [EnableCors]
    public abstract class WorkflowBaseController<TManager, TWorkProcessInstance> : Controller
        where TManager : WorkflowManager<ApplicationDbContext, TWorkProcessInstance>
        where TWorkProcessInstance : ProcessInstance

    {
        protected readonly ApplicationDbContext DbContext;
        protected TManager OrderManager;

        protected WorkflowBaseController(TManager orderManager, ApplicationDbContext dbContext)
        {
            OrderManager = orderManager;
            DbContext = dbContext;
        }

        [HttpGet("get/{id:int}")]
        public virtual IActionResult Get(int id)
        {
            var result = OrderManager.GetById(id);

            return Json(result);
        }

        [HttpGet("work-activity/{id:int}")]
        public virtual IActionResult GetByWorkActionResult(int id)
        {
            var iem = OrderManager.GetWorkActivity(id, true);

            return Json(iem);
        }


        [HttpPost("reject/{id:int}")]
        [ModelValidteFilter]
        public IActionResult Reject([FromRoute] int id, [FromBody] WorkflowDepositViewModel model)
        {
            var activity = OrderManager.Reject(id, model.Comment, out var workActivities);
            return Json(new
            {
                workActivity = activity,
                successed = true,
                message = true ? "处理成功" : "没有可以退回流程"
            });
        }

        [HttpPost("resolve/{id:int}")]
        [ModelValidteFilter]
        public IActionResult Resolve([FromRoute] int id, [FromBody] WorkflowDepositViewModel model)
        {
            var activity
                = OrderManager.Resolve(id, model.Comment, out var workActivities);
            if (model.NextUserId != null && workActivities != null)
            {
                var user = DbContext.Users.FirstOrDefault(f => f.Id == model.NextUserId);
                foreach (var nextActivity in workActivities)
                {
                    nextActivity.AssignTo(user);
                    DbContext.Update(nextActivity);
                }
            }

            DbContext.SaveChanges();
            return Json(new
            {
                workActivity = activity,
                successed = true,
                message = "处理成功"
            });
        }
    }
}